package cn.tonystack.service.impl;

import cn.tonystack.constants.Constants;
import cn.tonystack.dao.IOrderDao;
import cn.tonystack.domain.po.PayOrder;
import cn.tonystack.domain.req.ShopCartReq;
import cn.tonystack.domain.res.PayOrderRes;
import cn.tonystack.domain.vo.ProductVO;
import cn.tonystack.service.IOrderService;
import cn.tonystack.service.rpc.ProductRPC;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;

/**
 * @description：TODO
 * @author： tony.pan
 * @create： 2024/10/11 0:04
 */
@Slf4j
@Service
public class OrderServiceImpl implements IOrderService {

    @Resource
    private IOrderDao orderDao;

    @Resource
    private ProductRPC productRPC;

    @Override
    public PayOrderRes createOrder(ShopCartReq shopCartReq) throws Exception {
        //查询当前用户下是否存在未支付的订单
        PayOrder payOrderReq  = new PayOrder();
        payOrderReq.setUserId(shopCartReq.getUserId());
        payOrderReq.setProductId(shopCartReq.getProductId());

        PayOrder unpaidPayOrder = orderDao.queryUnPayOrder(payOrderReq);

        if(null != unpaidPayOrder && Constants.OrderStatusEnum.PAY_WAIT.getCode().equals(unpaidPayOrder.getStatus())) {
            log.info("创建订单存在， 已存在未支付的订单。userId:{} productId:{} orderId:{}", shopCartReq.getUserId(), shopCartReq.getProductId(),unpaidPayOrder.getOrderId());
            return PayOrderRes.builder()
                    .orderId(unpaidPayOrder.getOrderId())
                    .payUrl(unpaidPayOrder.getPayUrl())
                    .build();
        } else if(null != unpaidPayOrder && Constants.OrderStatusEnum.CREATE.getCode().equals(unpaidPayOrder.getStatus())) {
            // todo tony
        }

        //查询商品并创建订单
        ProductVO productVO = productRPC.queryProductByProductId(shopCartReq.getProductId());
        String orderId = RandomStringUtils.randomNumeric(16);
        orderDao.insert(PayOrder.builder()
                .userId(shopCartReq.getUserId())
                .productId(shopCartReq.getProductId())
                .productName(productVO.getProductName())
                .orderId(orderId)
                .totalAmount(productVO.getPrice())
                .orderTime(new Date())
                .status(Constants.OrderStatusEnum.CREATE.getCode())
                .build());


        //创建支付订单 并且回写状态



        return PayOrderRes.builder()
                .orderId(orderId)
                .payUrl("1")
                .build();
    }
}
